<?php
/**
 * @name ErrorController
 * @desc 错误控制器, 在发生未捕获的异常时刻被调用
 * @see http://www.php.net/manual/en/yaf-dispatcher.catchexception.php
 * @author desktop-53vhird\huizhou
 */
class ErrorController extends Yaf_Controller_Abstract {

    private $code;
    private $msg;
    private $errorCode;
    private $status;
    public $path = '/../log/';

    public function errorAction($exception) {
        // 设置时区
        date_default_timezone_set('Asia/ShangHai');
        // 存储错误路径
        $this->path = dirname(__FILE__)  . $this->path;
        $request = $this->getRequest();
        if($exception instanceof BaseException){
             // 如果是自定义的异常
             $this->code = $exception->code;
             $this->msg = $exception->msg;
             $this->errorCode = $exception->errorCode;
             $this->status = $exception->status;
        }else {
             $this->code = 500;
             $this->msg = '服务器错误';
             $this->recordErrorLog($exception);
        }
        $result = [
            'code' => $this->code,
            'msg'=> $this->msg,
            'request_url'=> $request->getRequestUri()
        ];
        echo json_encode($result,$this->code);
        return false;

    }


    private function recordErrorLog($exception){
    $request = $this->getRequest();
    // 日志初始化，只有高于error级别才会记录下去
        $err_arr =
           'ErrorLevel: Fatal'."\r\n".
           'code:'.$this->code."\r\n".
           'msg:'.$this->msg."\r\n".
           'request_url:'.$request->getRequestUri();
        // 记录日志，设置日志级别
        $this->write($err_arr);
    }

    /**
     *   @void
     *	创建并写入
     */
    public function write($message) {

        $date = new DateTime();
        $log = $this->path . $date->format('Y-m-d').".txt";
        if(is_dir($this->path)) {
            if(!file_exists($log)) {
                $fh  = fopen($log, 'a+') or die("Fatal Error !");
                $logcontent = "[Time : " . $date->format('Y-m-d H:i:s')."]"."\r\n" . $message ."\r\n";
                fwrite($fh, $logcontent);
                fclose($fh);
            }else {
                $this->edit($log,$date, $message);
            }
        }else {
            if(mkdir($this->path,0777) === true) {
                $this->write($message);
            }
        }
    }

    /**
     *  @void
     *  修改并写入日志
     * @param string $log
     * @param DateTimeObject $date
     * @param string $message
     */
    private function edit($log,$date,$message) {
        $logcontent = "[Time : " . $date->format('Y-m-d H:i:s')."]"."\r\n" . $message ."\r\n\r\n";
        $logcontent = $logcontent . file_get_contents($log);
        file_put_contents($log, $logcontent);
    }

}
